package com.hzw.saas.service.user.service;

import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzw.saas.api.user.ICustomerRefService;
import com.hzw.saas.api.user.bo.CustomerRefBO;
import com.hzw.saas.common.util.SnowFlakeUtil;
import com.hzw.saas.service.user.mapper.CustomerRefMapper;
import com.hzw.saas.service.user.model.CustomerRef;
import org.springframework.stereotype.Service;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;

/**
 * @author zzl
 * @since 04/03/2021
 */
@Slf4j
@RequiredArgsConstructor
@Service("customerRefServiceImpl")
public class CustomerRefServiceImpl extends ServiceImpl<CustomerRefMapper, CustomerRef> implements ICustomerRefService, IService<CustomerRef> {

    private final MapperFacade mapperFacade;

    @Override
    public void add(CustomerRefBO customerRefBO) {
        if(StringUtil.isBlank(customerRefBO.getPid())) {
            customerRefBO.setPid(String.valueOf(SnowFlakeUtil.nextId()));
        }
        // 检查是否已有数据
        int count = super.lambdaQuery()
            .eq(CustomerRef::getStaffId, customerRefBO.getStaffId())
            .eq(CustomerRef::getUserId, customerRefBO.getUserId())
            .eq(CustomerRef::getRelation, customerRefBO.getRelation())
            .count();
        if (count > 0) {
            return;
        }
        this.save(mapperFacade.map(customerRefBO, CustomerRef.class));
    }

    @Override
    public void deleteByUserId(String userId) {
        this.remove(Wrappers.<CustomerRef>lambdaQuery().eq(CustomerRef::getUserId, userId));
    }

    @Override
    public void deleteByStaffIds(List<String> staffIds) {
        if(CollectionUtils.isEmpty(staffIds)) {
            return;
        }
        this.remove(Wrappers.<CustomerRef>lambdaQuery().in(CustomerRef::getStaffId, staffIds));
    }

    @Override
    public void addBatch(List<CustomerRefBO> customerRefBOS) {
        List<CustomerRef> customerRefs = mapperFacade.mapAsList(customerRefBOS, CustomerRef.class);
        this.saveBatch(customerRefs);
    }

    @Override
    public List<CustomerRefBO> search(CustomerRefBO customerRefBO) {
        CustomerRef customerRef = mapperFacade.map(customerRefBO, CustomerRef.class);
        List<CustomerRef> list = list(Wrappers.<CustomerRef>query().setEntity(customerRef));
        return mapperFacade.mapAsList(list, CustomerRefBO.class);
    }

}


